const AdminModel = require('../models/adminModel');
const { validateRequiredFields } = require('../utils/helpers');
const jwt = require('jsonwebtoken');
const { getConnection } = require('../config/db');

// JWT 密钥（在生产环境中应使用环境变量）
const JWT_SECRET = process.env.JWT_SECRET || 'xiqu_admin_secret_key';

class AdminController {
  // 管理员登录
  static async login(req, res) {
    try {
      // 验证必需字段
      validateRequiredFields(req.body, ['username', 'password']);
      
      const { username, password } = req.body;
      
      console.log(`尝试登录用户: ${username}`);
      
      // 查找管理员用户
      const admin = await AdminModel.findByUsername(username);
      
      console.log('查询到的用户:', admin);
      
      if (!admin) {
        console.log('用户不存在');
        return res.status(401).json({
          code: 401,
          msg: '用户名或密码错误'
        });
      }
      
      // 验证密码
      console.log(`验证密码: ${password}`);
      console.log(`用户密码哈希: ${admin.password}`);
      const isValidPassword = await AdminModel.validatePassword(password, admin.password);
      
      console.log(`密码验证结果: ${isValidPassword}`);
      
      if (!isValidPassword) {
        return res.status(401).json({
          code: 401,
          msg: '用户名或密码错误'
        });
      }
      
      // 生成 JWT token
      const token = jwt.sign(
        { id: admin.id, username: admin.username },
        JWT_SECRET,
        { expiresIn: '24h' }
      );
      
      res.json({
        code: 200,
        msg: '登录成功',
        data: {
          token,
          admin: {
            id: admin.id,
            username: admin.username
          }
        }
      });
    } catch (error) {
      console.error('管理员登录失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 验证管理员 token
  static async verifyToken(req, res) {
    try {
      const token = req.headers['authorization'];
      
      if (!token) {
        return res.status(401).json({
          code: 401,
          msg: '未提供访问令牌'
        });
      }
      
      // 验证 token
      const decoded = jwt.verify(token.replace('Bearer ', ''), JWT_SECRET);
      
      res.json({
        code: 200,
        msg: '令牌有效',
        data: {
          admin: {
            id: decoded.id,
            username: decoded.username
          }
        }
      });
    } catch (error) {
      console.error('令牌验证失败:', error);
      res.status(401).json({
        code: 401,
        msg: '无效的访问令牌'
      });
    }
  }

  // 修改密码
  static async changePassword(req, res) {
    try {
      // 验证必需字段
      validateRequiredFields(req.body, ['oldPassword', 'newPassword']);
      
      const { adminId } = req;
      const { oldPassword, newPassword } = req.body;
      
      // 获取管理员信息
      const admin = await AdminModel.findByUsername(req.admin.username);
      
      if (!admin) {
        return res.status(404).json({
          code: 404,
          msg: '管理员不存在'
        });
      }
      
      // 验证旧密码
      const isValidOldPassword = await AdminModel.validatePassword(oldPassword, admin.password);
      
      if (!isValidOldPassword) {
        return res.status(401).json({
          code: 401,
          msg: '旧密码错误'
        });
      }
      
      // 更新密码
      await AdminModel.updatePassword(adminId, newPassword);
      
      res.json({
        code: 200,
        msg: '密码修改成功'
      });
    } catch (error) {
      console.error('修改密码失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 管理端统计
  static async getStats(req, res) {
    try {
      const connection = await getConnection();
      try {
        // 总视频数与总播放量
        const [totalRows] = await connection.execute('SELECT COUNT(*) AS totalVideos, COALESCE(SUM(play_count),0) AS totalPlays FROM videos');
        const summary = totalRows && totalRows[0] ? totalRows[0] : { totalVideos: 0, totalPlays: 0 };

        // 各剧种视频数量/播放量排行 TOP10
        const genreSql = `
          SELECT g.id, g.name,
                 COUNT(vg.video_id) AS video_count,
                 COALESCE(SUM(v.play_count),0) AS play_count
          FROM genres g
          LEFT JOIN video_genres vg ON g.id = vg.genre_id
          LEFT JOIN videos v ON vg.video_id = v.id
          GROUP BY g.id, g.name
          ORDER BY play_count DESC, video_count DESC
          LIMIT 10
        `;
        const [genreRows] = await connection.execute(genreSql);

        // 近7天新增视频数（按天）
        const recentSql = `
          SELECT DATE(created_at) AS date, COUNT(*) AS count
          FROM videos
          WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
          GROUP BY DATE(created_at)
          ORDER BY date ASC
        `;
        const [recentRows] = await connection.execute(recentSql);

        res.json({
          code: 200,
          msg: '获取成功',
          data: {
            summary,
            genresTop: genreRows || [],
            recentUploads: recentRows || []
          }
        });
      } finally {
        connection.release();
      }
    } catch (error) {
      console.error('获取统计失败:', error);
      res.status(500).json({ code: 500, msg: error.message || '服务器错误' });
    }
  }
}

module.exports = AdminController;